package org.sys.transporttrainsys.controller;

import org.sys.transporttrainsys.entity.Consultation;
import org.sys.transporttrainsys.service.ConsultationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(origins = "http://localhost:5173")
@RequestMapping("/api/consultations")
public class ConsultationController {

    @Autowired
    private ConsultationService consultationService;

    @GetMapping
    public List<Consultation> getAllConsultations() {
        return consultationService.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Consultation> getConsultationById(@PathVariable Long id) {
        Consultation consultation = consultationService.findById(id);
        return consultation != null ? ResponseEntity.ok(consultation) : ResponseEntity.notFound().build();
    }



    @PostMapping
    public Consultation createConsultation(@RequestBody Consultation consultation) {
        return consultationService.save(consultation);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Consultation> updateConsultation(@PathVariable Long id, @RequestBody Consultation consultation) {
        consultation.setId(id);
        Consultation updatedConsultation = consultationService.save(consultation);
        return ResponseEntity.ok(updatedConsultation);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteConsultation(@PathVariable Long id) {
        consultationService.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/search")
    public List<Consultation> getConsultations(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String status) {
        if (title != null && status != null) {
            return consultationService.findByTitleAndStatus(title, status);
        } else if (title != null) {
            return consultationService.findByTitle(title);
        } else if (status != null) {
            return consultationService.findByStatus(status);
        } else {
            return consultationService.findAll();
        }
    }
}